package com.aitaoxue.palx;

import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongIM.ConversationBehaviorListener;
import io.rong.imkit.RongIM.UserInfoProvider;
import io.rong.imkit.widget.provider.CameraInputProvider;
import io.rong.imkit.widget.provider.InputProvider;
import io.rong.imkit.widget.provider.LocationInputProvider;
import io.rong.imlib.RongIMClient.ConnectionStatusListener;
import io.rong.imlib.RongIMClient.OnReceiveMessageListener;
import io.rong.imlib.RongIMClient.OnReceivePushMessageListener;
import io.rong.imlib.model.Conversation.ConversationType;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;
import io.rong.message.LocationMessage;
import io.rong.notification.PushNotificationMessage;

import java.util.HashSet;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.aitaoxue.palx.api.ApiHttpClient;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.bean.UserInfos;
import com.aitaoxue.palx.db.RongyunContext;
import com.aitaoxue.palx.im.PhotoCollectionsProvider;
import com.aitaoxue.palx.im.message.PushMessage;
import com.aitaoxue.palx.ui.MainActivity;
import com.aitaoxue.palx.ui.PersonCenterActivity;
import com.aitaoxue.palx.ui.PhotoActivity;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 融云SDK事件监听处理。 把事件统一处理，开发者可直接复制到自己的项目中去使用。
 * <p/>
 * 该类包含的监听事件有： 1、消息接收器：OnReceiveMessageListener。
 * 2、发出消息接收器：OnSendMessageListener。 3、用户信息提供者：GetUserInfoProvider。
 * 4、好友信息提供者：GetFriendsProvider。 5、群组信息提供者：GetGroupInfoProvider。
 * 7、连接状态监听器，以获取连接相关状态：ConnectionStatusListener。 8、地理位置提供者：LocationProvider。
 * 9、自定义 push 通知： OnReceivePushMessageListener。
 * 10、会话列表界面操作的监听器：ConversationListBehaviorListener。
 */
public class RongCloudEvent implements Callback, UserInfoProvider,
		ConversationBehaviorListener, ConnectionStatusListener,
		OnReceiveMessageListener, OnReceivePushMessageListener {

	private static final String TAG = RongCloudEvent.class.getSimpleName();

	private static RongCloudEvent instance;

	private Context mContext;
	private Handler mHandler;

	// 保存查找过的个人信息
	private HashSet<String> findSet;

	private RongCloudEvent(Context context) {
		mContext = context;
		findSet = new HashSet<>();
		initDefaultListener();
		mHandler = new Handler(this);
	}

	public static void init(Context context) {
		if (instance == null) {

			synchronized (RongCloudEvent.class) {
				if (instance == null) {
					instance = new RongCloudEvent(context);
				}
			}
		}
	}

	public static RongCloudEvent getInstance() {
		return instance;
	}

	@Override
	public boolean handleMessage(Message msg) {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * RongIM.init(this)后直接可注册的listener
	 */
	private void initDefaultListener() {
		// 设置用户信息提供者
		RongIM.setUserInfoProvider(this, true);
		// 设置会话界面操作的监听器
		RongIM.setConversationBehaviorListener(this);
		// 设置自定义push通知
		RongIM.setOnReceivePushMessageListener(this);
	}

	/**
	 * 连接成功后设置的listener
	 */
	@SuppressWarnings("static-access")
	public void setOtherListener() {
		// 设置消息接受监听器
		RongIM.getInstance().getRongIMClient()
				.setOnReceiveMessageListener(this);

		// 扩展功能自定义
		InputProvider.ExtendProvider[] provider = {
				new PhotoCollectionsProvider(RongContext.getInstance()),
				// new ImageInputProvider(RongContext.getInstance()),
				new CameraInputProvider(RongContext.getInstance()),
		// new LocationInputProvider(RongContext.getInstance())
		};

		RongIM.getInstance().resetInputExtensionProvider(
				ConversationType.PRIVATE, provider);
		RongIM.getInstance().resetInputExtensionProvider(
				ConversationType.SYSTEM, provider);

		RongIM.getInstance().getRongIMClient()
				.setConnectionStatusListener(this);
	}

	@Override
	public UserInfo getUserInfo(String userId) {
		Log.d(TAG, "getUserInfo:" + userId);

		UserInfos info = RongyunContext.getInstance().getUserInfoById(userId);

		if (!findSet.contains(userId)) {
			findSet.add(userId);
			AitaoXueApi.getUserInfo(userId, getUserInfoHandler);
		}

		if (info == null) {
			return null;
		} else {
			return new UserInfo(userId, info.getUsername(),
					Uri.parse(ApiHttpClient.HEADER_PREFIX + info.getPortrait()));
		}
	}

	private AsyncHttpResponseHandler getUserInfoHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String res = new String(arg2);

			try {
				JSONObject json = new JSONObject(res);
				JSONArray array = json.getJSONArray("content");
				JSONObject jsonObject = array.getJSONObject(0);
				String name = jsonObject.getString("name");
				String head_thumb = jsonObject.getString("header");
				String userId = jsonObject.getString("userId");

				UserInfos infos = RongyunContext.getInstance().getUserInfoById(
						userId);
				if (infos == null || !infos.getUsername().equals(name)
						|| !infos.getPortrait().equals(head_thumb)) {
					UserInfos tmp = new UserInfos();
					tmp.setUserid(userId);
					tmp.setUsername(name);
					tmp.setPortrait(head_thumb);

					RongyunContext.getInstance().insertOrReplaceUserInfo(tmp);
					if (infos != null) {
						RongIM.getInstance().refreshUserInfoCache(
								new UserInfo(userId, name, Uri
										.parse(ApiHttpClient.HEADER_PREFIX
												+ head_thumb)));
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			Log.d(TAG, "getUserInfo:" + res);
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			System.out.println("here");

		}
	};

	// 点击消息
	@Override
	public boolean onMessageClick(Context context, View view,
			io.rong.imlib.model.Message message) {
		if (message.getContent() instanceof ImageMessage) {
			ImageMessage imageMessage = (ImageMessage) message.getContent();

			Intent intent = new Intent(context, PhotoActivity.class);
			intent.putExtra("fromChat", true);
			intent.putExtra("photo",
					imageMessage.getLocalUri() == null ? imageMessage
							.getRemoteUri().toString() : imageMessage
							.getLocalUri().toString());
			context.startActivity(intent);
		}

		return false;
	}

	@Override
	public boolean onMessageLinkClick(Context arg0, String arg1) {
		return false;
	}

	@Override
	public boolean onMessageLongClick(Context arg0, View arg1,
			io.rong.imlib.model.Message arg2) {
		return false;
	}

	// 点击用户头像
	@Override
	public boolean onUserPortraitClick(Context context, ConversationType type,
			UserInfo info) {
		String userId = info.getUserId();
		Intent intent = new Intent(context, PersonCenterActivity.class);

		// 自己
		if (userId
				.equals(AppContext.getInstance().getProperty("user.username"))) {
			intent.putExtra("isMine", true);
			context.startActivity(intent);
		} else {
			// 家长没有个人主页
		}

		return false;
	}

	// 长按用户头像
	@Override
	public boolean onUserPortraitLongClick(Context arg0, ConversationType arg1,
			UserInfo arg2) {
		return false;
	}

	@Override
	public void onChanged(ConnectionStatus status) {
		switch (status) {
		case CONNECTED: // 连接成功
			Log.d(TAG, "上线");
			break;
		case CONNECTING: // 连接中
			break;
		case DISCONNECTED: // 断开连接
			Log.d(TAG, "下线");
			break;
		case NETWORK_UNAVAILABLE: // 网络不可用
			break;
		case KICKED_OFFLINE_BY_OTHER_CLIENT: // 用户帐号在其他设备登录
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onReceived(io.rong.imlib.model.Message message, int arg1) {

		MessageContent messageContent = message.getContent();
		
		Log.d(TAG, "heiheihei");

		if (messageContent instanceof PushMessage) {
			// 触发ui改变
			Intent in = new Intent();
			in.setAction(MainActivity.PUSH_TEST);
			mContext.sendBroadcast(in);
		}

		if (messageContent instanceof PushMessage) {
			System.out.println("here");
		}

		return false;
	}

	@Override
	public boolean onReceivePushMessage(PushNotificationMessage message) {
		MessageContent messageContent=message.getContent();
		
		//Log.d(TAG, "heiheihei");

		return false;
	}

}
